package com.hyb.algorithm.data.struct.list;

/**
 * @Author: huyanbing
 * @Date: 2021/9/5 5:04 下午
 * 25. K 个一组翻转链表
 * https://leetcode-cn.com/problems/reverse-nodes-in-k-group/
 */
public class ReverseKGroup {

    public static void main(String[] args) {
        ReverseKGroup exe=new ReverseKGroup();

        int[] nums = new int[]{1, 2, 3, 4, 5};

        int len = nums.length;

        ListNode head = new ListNode(1);
        ListNode temp = head;
        for (int i = 1; i < len; i++) {
            ListNode listNode = new ListNode(nums[i]);

            temp.next = listNode;
            temp = listNode;
        }

        ListNode res = exe.reverseKGroup(head, 2);

        System.out.println(res);
    }

    public ListNode reverseKGroup(ListNode head, int k) {
        if (head == null) {
            return null;
        }
        ListNode a = head, b = head;
        //前闭后开  [a,b)
        for (int i = 0; i < k; i++) {
            //不够k个 不用反转
            if (b == null) {
                return head;
            }
            b = b.next;
        }

        //新head  1->2  反转后 2 为 newHead
        ListNode newHead = reverse(a, b);

        // a 连接 1->2 反转后 用 2->1->reverseKGroup(b,k)
        a.next = reverseKGroup(b, k);

        return newHead;
    }


    public ListNode reverse1(ListNode a, ListNode b) {
        ListNode pre = null;
        ListNode cur = a;
        ListNode next = a;

        while (cur != b && cur != null) {
            //临时存储下一个节点
            next = cur.next;
            //指针反向
            cur.next = pre;
            //pre 前移
            pre = cur;
            //cur 前移动
            cur = next;
        }
        return pre;
    }

    /** 反转区间 [a, b) 的元素，注意是左闭右开 */
    public  ListNode reverse(ListNode a, ListNode b) {
        ListNode pre, cur, nxt;
        pre = null; cur = a; nxt = a;
        // while 终止的条件改一下就行了
        while (cur != b) {
            nxt = cur.next;
            cur.next = pre;
            pre = cur;
            cur = nxt;
        }
        // 返回反转后的头结点
        return pre;
    }
}
